﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CoreGraphics;
using Foundation;
using mb;
using mb.iOS;
using Masonry;
using MyExtensions;
using PagerManager;
using Ricardo.SDWebImage.iOS;
using UIKit;
using static libmp.DataStore;

namespace libmp
{
    class VCHomeMovie : VCExMovieList
    {
        UIView rcmView;
        MyScrollView adView;
        public UIPanGestureRecognizer ParentPanGR;

        List<DataStore.VideoItem> movieInfoList;
        List<InsertItem> insertItems = new List<InsertItem>();

        public VCHomeMovie()
        {

        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            View.BackgroundColor = UIColor.White;
            // logger.Log(" movieInfoList ------> " + movieInfoList);

            User.me.OnChanged += (user) =>
            {
                logger.Log("user changed...");
            };

            CreateADView();
            this.dataSource = DataStore.store.GetRecommendVideoList();
            this.Reload();
        }

        protected override int[] GetInsertIndex() => insertItems.Select(v => v.insertBefore).ToArray();
        protected override InsertItem GetInsertViewConfig(int idx) { return insertItems[idx]; }

        void CreateADView()
        {
            var container = new UIView();
            insertItems.Add(new InsertItem()
            {
                insertBefore = 0,
                    view = container,
                    height = 150,
                    stickyHeight = 0,

            });

            //
            adView = new MyScrollView()
            {
                Bounces = false,
                // BackgroundColor = UIColor.Gray,
                PagingEnabled = true,
            };
            adView.SetParent(container);
            adView.Layer.CornerRadius = 10;
            adView.MakeConstraints(m => m.Edges.EqualTo(container).With.Insets(new UIEdgeInsets(10, 10, 10, 10)));

            adView.MyShouldRecognizeSimultaneously = (v, rg1, rg2) =>
            {
                var rg1Pan = rg1 as UIPanGestureRecognizer;
                if (rg1Pan != null && rg2 == ParentPanGR)
                {
                    var w = adView.Bounds.Width;
                    var rw = adView.ContentSize.Width - adView.ContentOffset.X;
                    var panv = rg1Pan.VelocityInView(rg1Pan.View);
                    // logger.Log("checking parent gr...", adView.ContentOffset, adView.ContentSize, rw <= w);
                    // logger.Log("current dir", panv);
                    if (rw <= w && panv.X < 0)
                    {
                        logger.Log("last page, enable parent gr");
                        return true;
                    }
                }

                return false;
            };
            adView.MyLayoutSubviews = () =>
            {
                var w = adView.Bounds.Width;
                var h = adView.Bounds.Height;
                int nc = 0;
                for (var it = adView.Subviews.OfType<UIImageView>().GetEnumerator(); it.MoveNext();)
                {
                    // logger.Log("subview", nc, it.Current.Tag);
                    if (it.Current.Tag >= 100)
                    {
                        it.Current.Frame = new CGRect(nc * w, 0, w, h);
                        nc++;
                    }
                }
                adView.ContentSize = new CGSize(w * nc, h);
                // logger.Log("layout subview", nc, w, h);
            };

            // foreach (var img in libmp.DataStore.store.onlineConfig.adImages)
            // {
            //     var imgView = new UIImageView();
            //     mb.iOS.Util.SetUIImageViewUrl(imgView, img.imgpath);
            //     imgView.SetParent(adView);
            //     imgView.Tag = 100;
            //     var imgButton = new UIButton();
            //     imgButton.SetParent(adView);
            //     imgButton.MakeConstraints(m =>
            //     {
            //         m.Right.EqualTo(imgView);
            //         m.Top.EqualTo(imgView);
            //         m.Left.EqualTo(imgView);
            //         m.Height.EqualTo(NSObject.FromObject(150));
            //     });
            //     imgButton.TouchUpInside += (s, e) =>
            //     {
            //         logger.Log("点击====>" + img.imgid);
            //         Xamarin.Essentials.Browser.OpenAsync(img.imghref, Xamarin.Essentials.BrowserLaunchMode.External);
            //         User.me.Notify("clickad", LitJson.JsonMapper.ToJson(new { imgid = img.imgid }));
            //     };
            // }

            var page = new UIPageControl();
            page.SetParent(container);
            page.MakeConstraints(m =>
            {
                m.Bottom.EqualTo(container).Offset(15);
                // m.Top.EqualTo(adView).Offset(100);
                m.CenterX.EqualTo(container);
            });
            // page.Pages = libmp.DataStore.store.onlineConfig.adImages.Count;
            page.CurrentPage = 0;
            page.PageIndicatorTintColor = UIColor.Black;
            page.CurrentPageIndicatorTintColor = Util.MainColor;
            page.Enabled = false;

            adView.ShowsHorizontalScrollIndicator = false;
            adView.DecelerationEnded += (s, e) =>
            {
                logger.Log("scrolled");
                var x = adView.ContentOffset.X;
                var w = adView.Frame.Width;
                page.CurrentPage = (int) Math.Ceiling(x / w);
            };
        }

    }
}